//
//  messageSystemTableViewCell.m
//  SoundPill
//
//  Created by 宋旭东 on 16/4/21.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "messageSystemTableViewCell.h"
#import "UIViewExt.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "WZLBadgeImport.h"

#define kleftGap  10
#define kupGap   12
#define kDeviceWidth [UIScreen mainScreen].bounds.size.width
#define kImageViewWidth 40
#define kImageViewHeight 40
#define kLabelWidth [UIScreen mainScreen].bounds.size.width*0.35
#define kLabelHeight 60
@interface messageSystemTableViewCell ()
@property (strong, nonatomic)    UIImageView *lineImage;
@property (strong, nonatomic) NSArray *actionArray;
@end

@implementation messageSystemTableViewCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self initSubViews];
        self.backgroundColor=[UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.actionArray = [NSArray arrayWithObjects:@"people",@"pay",@"love",@"payed",@"loved",@"thank",@"comment",@"reply", nil];
    }
    return self;
}
- (void)initSubViews
{
    self.avatar = [[UIImageView alloc] initWithFrame:CGRectZero];
    _avatar.userInteractionEnabled = YES;
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarClick:)];
    [_avatar addGestureRecognizer:recognizer];
    [self addSubview:_avatar];
    
    self.redView = [[UIView alloc] initWithFrame:CGRectZero];
    _redView.backgroundColor = [UIColor redColor];
    [self addSubview:_redView];
    
    self.username = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_username];
    
//    self.date = [[UILabel alloc] initWithFrame:CGRectZero];
//    [self addSubview:_date];
    
    // 描述
    self.detaillable = [[UILabel alloc] initWithFrame:CGRectZero];
//    _detaillable.backgroundColor = [UIColor whiteColor];
    [self addSubview:_detaillable];
    
    self.thanksBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_thanksBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _thanksBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [_thanksBtn addTarget:self action:@selector(thankBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_thanksBtn];
    
    self.lineImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_lineImage];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _avatar.frame = CGRectMake(kleftGap, kupGap, self.height - (2 * kupGap), self.height - (2 * kupGap));
    [_avatar setImageWithURL:[NSURL URLWithString:_model.avatar] placeholderImage:[UIImage imageNamed:@"default_head"]];
    _avatar.backgroundColor=[UIColor whiteColor];
    
    _username.frame = CGRectMake(_avatar.right + 10, _avatar.top, self.frame.size.width - (_avatar.right + 20), _avatar.height / 2);
    _username.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
    _username.textColor = [UIColor blackColor];
    _username.text = _model.username;//
    
//    _date.frame = CGRectMake(_avatar.right + 10, _username.top,  self.frame.size.width - (_avatar.right + 20), _avatar.height / 2);
//    _date.font = [UIFont systemFontOfSize:13];
//    _date.textAlignment = NSTextAlignmentRight;
//    _date.textColor = [UIColor colorWithRed:0.717 green:0.719 blue:0.727 alpha:1.000];
//    [self resetDate:_model.created_at];
    
    _thanksBtn.frame = CGRectMake(0, 0, _avatar.width, _avatar.height / 2);
    _thanksBtn.center = CGPointMake(self.width - _avatar.width / 2 - 15, self.height / 2);
    if ([_model.action isEqualToString:@"pay"] || [_model.action isEqualToString:@"love"]) {
        [_thanksBtn setTitle:@"感谢" forState: UIControlStateNormal];
        _thanksBtn.backgroundColor = [UIColor blackColor];
        _thanksBtn.hidden = NO;
    } else if ([_model.action isEqualToString:@"payed"] || [_model.action isEqualToString:@"loved"]){
        [_thanksBtn setTitle:@"已谢" forState: UIControlStateNormal];
        _thanksBtn.backgroundColor = [UIColor grayColor];
        _thanksBtn.hidden = NO;
    } else if ([_model.action isEqualToString:@"people"]) {
        if (_model.follow.boolValue == YES) {
            [_thanksBtn setTitle:@"互粉" forState: UIControlStateNormal];
            _thanksBtn.backgroundColor = [UIColor grayColor];
            _thanksBtn.hidden =  NO;
        } else {
            [_thanksBtn setTitle:@"关注" forState: UIControlStateNormal];
            _thanksBtn.backgroundColor = [UIColor  blackColor];
            _thanksBtn.hidden =  NO;
        }
    } else {
        _thanksBtn.hidden = YES;
    }
    _detaillable.textColor = [UIColor grayColor];
    _detaillable.font = [UIFont systemFontOfSize:14];
    _detaillable.text = _model.message;

    _detaillable.frame = CGRectMake(_avatar.right + 10, _username.bottom + 5,_thanksBtn.left - _avatar.right - 20, 16);
    _lineImage.backgroundColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    _lineImage.frame = CGRectMake(0, self.frame.size.height, self.width, 0.5);
    _redView.frame = CGRectMake(0, 0, 8, 8);
    _redView.center = CGPointMake(_avatar.right, _avatar.top);
    _redView.layer.cornerRadius = 4;
    if (_model.isread.intValue == 0) {
        _redView.hidden = NO;
    } else {
        _redView.hidden = YES;
    }
}
- (void)thankBtnClick:(UIButton *)sender
{
    sender.backgroundColor = [UIColor grayColor];
    if ([sender.titleLabel.text isEqualToString:@"感谢"]) {
        [sender setTitle:@"已谢" forState: UIControlStateNormal];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_model.id,@"id", nil];
        NSString *showURL = @"http://123.57.1.143/api/message/thank";
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
        [manager POST:showURL parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
  
    } else if ([sender.titleLabel.text isEqualToString:@"关注"]) {
        [sender setTitle:@"互粉" forState: UIControlStateNormal];
        AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
        NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/follow", _model.userid];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
        [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
    NSUInteger index = [_actionArray indexOfObject:_model.action];
    _actBlock(index);
}
- (void)avatarClick:(UITapGestureRecognizer *)recognizer
{
    _block(@"people",_model.userid);
}
- (void)resetDate:(NSString *)dateStr
{
    if (![dateStr isEqualToString:@"一秒前"]) {
        NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
        [gregorian setFirstWeekday:2];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *fromDate;
        NSDate *toDate;
        [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:[dateFormatter dateFromString:dateStr]];
        [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[NSDate date]];
        NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
        if (dayComponents.day == 0) {
            //        显示今天
            _date.text = [dateStr substringFromIndex:11];
        } else if (dayComponents.day == 1) {
            //        显示昨天
            _date.text = @"昨天";
        } else if (dayComponents.day < 7) {
            //        显示星期
            NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
            NSDate *date = [dateFormatter dateFromString:dateStr];
            NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
            NSDateComponents *theComponents = [gregorian components:calendarUnit fromDate:date];
            _date.text = weekdays[theComponents.weekday];
        } else{
            _date.text = [dateStr substringToIndex:10];
        }
    } else {
        _date.text = dateStr;
    }
}
@end
